package com.qmx.qmxapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.ImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.qmx.qmxapp.R;
import com.qmx.qmxapp.base.BaseDetailActivity;
import com.qmx.qmxapp.bean.LzyResponse;
import com.qmx.qmxapp.callback.JsonCallback;
import com.qmx.qmxapp.constant.AppConstant;
import com.qmx.qmxapp.constant.ComParamContact;
import com.qmx.qmxapp.realm.TokenList;
import com.qmx.qmxapp.token.TokenManager;
import com.qmx.qmxapp.view.NumberProgressBar;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;

public class FormUploadActivity extends BaseDetailActivity {

    @BindView(R.id.formUpload)
    Button btnFormUpload;
    @BindView(R.id.downloadSize)
    TextView tvDownloadSize;
    @BindView(R.id.tvProgress)
    TextView tvProgress;
    @BindView(R.id.netSpeed)
    TextView tvNetSpeed;
    @BindView(R.id.pbProgress)
    NumberProgressBar pbProgress;
    @BindView(R.id.images)
    TextView tvImages;

    private ArrayList<ImageItem> imageItems;
    private NumberFormat numberFormat;
    private String __TOKEN__ = "";
    private Realm realm;
    private String roomId = "";

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_form_upload);
        ButterKnife.bind(this);
        setTitle("文件上传");
        realm = Realm.getDefaultInstance();
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        roomId = this.getIntent().getStringExtra("roomId");
        token();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Activity销毁时，取消网络请求
        OkGo.getInstance().cancelTag(this);
        realm.isClosed();
    }

    @OnClick(R.id.selectImage)
    public void selectImage(View view) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Activity activity, String path, ImageView imageView, int width, int height) {
                Glide.with(FormUploadActivity.this)
                        .load(path)
                        .into(imageView);
            }

            @Override
            public void clearMemoryCache() {

            }
        });
        imagePicker.setMultiMode(true);   //多选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(9);    //最多选择9张
        imagePicker.setCrop(false);       //不进行裁剪
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItems != null && imageItems.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < imageItems.size(); i++) {
                        if (i == imageItems.size() - 1)
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path);
                        else
                            sb.append("图片").append(i + 1).append(" ： ").append(imageItems.get(i).path).append("\n");
                    }
                    tvImages.setText(sb.toString());
                } else {
                    tvImages.setText("--");
                }
            } else {
                Toast.makeText(this, "没有选择图片", Toast.LENGTH_SHORT).show();
                tvImages.setText("--");
            }
        }
    }


    public void token() {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                TokenList list = realm.where(TokenList.class).findFirst();
                __TOKEN__ = list.getToken();
                list.deleteFromRealm();
                Log.i("btn_join_meeting", __TOKEN__ + "--------" + (realm.where(TokenList.class).findAll()).size());
            }
        });
    }

    @OnClick(R.id.formUpload)
    public void formUpload(View view) {
        if (roomId.isEmpty()) {
            return;
        }
        ArrayList<File> files = new ArrayList<>();
        if (imageItems != null && imageItems.size() > 0) {
            for (int i = 0; i < imageItems.size(); i++) {
                files.add(new File(imageItems.get(i).path));
            }
        }
        //拼接参数
        OkGo.<LzyResponse<String>>post(AppConstant.Url + ComParamContact.Images.PATH)
                .tag(this)
                .headers(ComParamContact.Images.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .params(ComParamContact.Images.__TOKEN__, __TOKEN__)
                .params(ComParamContact.Images.ROOM_ID, roomId)
                //                .params("file1",new File("文件路径"))   //这种方式为一个key，对应一个文件
                .addFileParams(ComParamContact.Images.IMAGES, files)           // 这种方式为同一个key，上传多个文件
                .execute(new JsonCallback<LzyResponse<String>>() {
                    @Override
                    public void onStart(Request<LzyResponse<String>, ? extends Request> request) {
                        btnFormUpload.setText("正在上传中...");
                    }

                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        handleResponse(response);
                        btnFormUpload.setText("上传完成");
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        //                        handleError(response);
                        btnFormUpload.setText("上传出错");
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        System.out.println("uploadProgress: " + progress);

                        String downloadLength = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);
                        String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
                        tvDownloadSize.setText(downloadLength + "/" + totalLength);
                        String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
                        tvNetSpeed.setText(String.format("%s/s", speed));
                        tvProgress.setText(numberFormat.format(progress.fraction));
                        pbProgress.setMax(10000);
                        pbProgress.setProgress((int) (progress.fraction * 10000));
                    }
                });
    }
}